package com.gitee.huanminabc.test;


import com.gitee.huanminabc.test.bo.WeekLyDate;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

public class DateWeekRangeProcessor {

    private final int year;
    private final int month;

    public DateWeekRangeProcessor(int year, int month) {
        this.year = year;
        this.month = month;
    }

    public DateWeekRangeProcessor(LocalDate date) {
        this.year = date.getYear();
        this.month = date.getMonthValue();
    }


    public List<WeekLyDate> processRange(LocalDate startDay, LocalDate endDay) {
        // 检查输入的有效性
        if (startDay.getYear() != year || endDay.getYear() != year) {
            throw new IllegalArgumentException("Date range must be within the same year: " + year);
        }
        if (startDay.getMonthValue() != month || endDay.getMonthValue() != month) {
            throw new IllegalArgumentException("Date range must be within the same month: " + month);
        }
        return processRange(startDay.getDayOfMonth(), endDay.getDayOfMonth());
    }


    public List<WeekLyDate> processRange(int startDay, int endDay) {
        List<WeekLyDate> result = new ArrayList<>();
        // 创建输入日期
        LocalDate startDate = LocalDate.of(year, month, startDay);
        LocalDate endDate = LocalDate.of(year, month, endDay);

        // 检查是否跨月
        if (startDate.getMonth() != endDate.getMonth()) {
            throw new IllegalArgumentException("Date range cannot cross months");
        }

        // 找周一
        LocalDate currentStart = findMonday(startDate);
        //如果开始时间的月小于当前月,就将开始时间设置为当前月的第一天
        if (currentStart.getMonthValue() < month) {
            currentStart = LocalDate.of(year, month, 1);
        }

        // 处理不跨月的情况
        while (currentStart.getMonthValue() == month) {
            // 找到这个周的周日
            LocalDate currentEndRange = findSunday(currentStart);

            // 如果这个周的开始日期已经超过了用户选择的结束日期，结束循环
            if (currentStart.getDayOfMonth() > endDay) {
                break;
            }

            //如果currentEndRange>当月
            if (currentEndRange.getMonthValue() > month) {
                currentEndRange = endDate;
            }
            // 添加完整的周
            result.add(new WeekLyDate(currentStart, currentEndRange));

            // 移动到下一个周一
            currentStart = currentEndRange.plusDays(1);
        }

        return result;
    }

    //LocalDate 找到这个时间的周日
    public LocalDate findSunday(LocalDate date) {
        return date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
    }

    //找周一
    public LocalDate findMonday(LocalDate date) {
        return date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
    }



}
